package com.jwdf.uda.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;

import com.jwdf.uda.R;
import com.jwdf.uda.bean.ExtraBaseQuestion;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.databinding.FragmentReplyDetailBinding;
import com.jwdf.uda.event.MessageNoticeEvent;
import com.jwdf.uda.event.TitleEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.UserReadMessageAction;
import com.jwdf.uda.ui.activity.presenter.ReplyDetailPresenter;
import com.jwdf.uda.ui.activity.view.IReplyDetailView;
import com.jwdf.uda.ui.adapter.ReplyDetailAdapter;
import com.jwdf.uda.ui.adapter.item.ReplyDetailItem;
import com.jwdf.uda.ui.fragment.base.BaseFragment;
import com.jwdf.uda.utils.AppBus;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.view.FilterMenu;
import com.jwdf.uda.view.XListView;
import com.jwdf.uda.view.dialog.ChoiceDialog;
import com.jwdf.uda.view.dialog.ConfirmDialog;
import com.squareup.otto.Subscribe;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Response;

/**
 * Created by Administrator on 2016/9/18.
 */
public class ReplyDetaiActivtiy extends AbsTitleBarActivity {
    private static final String EXTRA_ID = "id";
    private final static String EXTRA_MSG_ID = "msg_id";
    private static final String EXTRA_IS_AUTHOR = "is_author";
    private static final String EXTRA_VOTE_COUNT = "voteCount";
    private static final String EXTRA_BASE_QUESTION = "base_question";
    private FilterMenu mFilterMenu;

    public static void start(Context context, int id, boolean isAuthor, int voteCount, ExtraBaseQuestion baseQuestion) {
        Intent intent = new Intent(context, ReplyDetaiActivtiy.class);
        intent.putExtra(EXTRA_ID, id);
        intent.putExtra(EXTRA_IS_AUTHOR, isAuthor);
        intent.putExtra(EXTRA_VOTE_COUNT, voteCount);
        intent.putExtra(EXTRA_BASE_QUESTION, baseQuestion);
        context.startActivity(intent);
    }

    public static void start(Context context, int id) {
        Intent intent = new Intent(context, ReplyDetaiActivtiy.class);
        intent.putExtra(EXTRA_ID, id);
        context.startActivity(intent);
    }

    public static void start(Context context, int id, int msgId) {
        Intent intent = new Intent(context, ReplyDetaiActivtiy.class);
        intent.putExtra(EXTRA_ID, id);
        intent.putExtra(EXTRA_MSG_ID, msgId);
        context.startActivity(intent);
    }

    @Override
    protected String getTopTitle() {
        return getString(R.string.title_reply_detail);
    }

    @Override
    public void onTitleClick(View view) {
        if (View.VISIBLE == getSecondaryTitleVisibility()) {
            ExtraBaseQuestion extraBaseQuestion = (ExtraBaseQuestion) getIntent().getSerializableExtra(EXTRA_BASE_QUESTION);
            if (extraBaseQuestion != null) {
                if (extraBaseQuestion.getQuestionId() > 0) {
                    QuizDetailActivity.start(view.getContext(), extraBaseQuestion.getQuestionId(), extraBaseQuestion.isAuthor());
                } else {
                    finish();
                }
            } else {
                QuizDetailActivity.start(view.getContext(), ((ReplyDetailFragment) mFragment).getQuizId(), false);
            }
        }
    }

    @Override
    protected void onDestroy() {
        EventBusUtil.unregisterEvent(this);
        super.onDestroy();
    }

    public void onEventMainThread(TitleEvent event) {
        if (TitleEvent.EVENT_REPLY_TITLE == event.getEventType()) {
            setTopTitle(event.getTitle(),
                    !TextUtils.equals(event.getTitle(), getString(R.string.title_reply_detail)) ? View.VISIBLE : View.GONE);
            setSecondaryTitle(getString(R.string.title_reply_count, ((ReplyDetailFragment) mFragment).getReplyCount()));
        }
    }

    @Override
    protected BaseFragment onCreateContentFragment() {
        return new ReplyDetailFragment();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        boolean isAuthor = getIntent().getBooleanExtra(EXTRA_IS_AUTHOR, false);
        int messageId = getIntent().getIntExtra(EXTRA_MSG_ID, 0);
        mFilterMenu = createFilterMenu(this);
        List<String> items = new ArrayList<>();
        if (isAuthor) {
            items.add(getString(R.string.reply_delete));
            items.add(getString(R.string.reply_edit));
            items.add(getString(R.string.quiz_detail_share));
        } else {
            items.add(getString(R.string.quiz_detail_share));
            items.add(getString(R.string.do_report));
        }
        mFilterMenu.bindMenuData(items);
        mFilterMenu.setOnMenuItemSelectedListener(createMenuItemListener());
        super.onCreate(savedInstanceState);
        EventBusUtil.registerEvent(this);
        if (messageId != 0) {
            onNewRequestCall(UserReadMessageAction.newInstance(this, messageId).request(new AHttpService.IResCallback<PbBean.PbResUserReadMessage>() {
                @Override
                public void onCallback(int resultCode, Response<PbBean.PbResUserReadMessage> response, PbBean.PbBaseServerInfo baseServerInfo) {
                    if (HttpHelper.showError(ReplyDetaiActivtiy.this, resultCode, baseServerInfo, R.string.error_net)) {
                        return;
                    }
                    EventBusUtil.post(new MessageNoticeEvent(MessageNoticeEvent.HAS_READ_MESSAGE));
                }
            }));
        }
    }

    @Override
    protected void setupTitleView() {
        setOperateTitleIconAction(R.mipmap.ic_detail_menu_more);
    }

    @Override
    protected Bundle onPutArguments() {
        Bundle args = new Bundle();
        args.putInt(EXTRA_ID, getIntent().getIntExtra(EXTRA_ID, 0));
        args.putInt(EXTRA_VOTE_COUNT, getIntent().getIntExtra(EXTRA_VOTE_COUNT, 0));
        args.putSerializable(EXTRA_BASE_QUESTION, getIntent().getSerializableExtra(EXTRA_BASE_QUESTION));
        return args;
    }

    @Override
    public void onHeadActionClick(View view) {
        if (((ReplyDetailFragment) mFragment).titleMenuEnabled()) {
            mFilterMenu.show(view);
        }
    }

    private FilterMenu.MenuItemAdapter.OnMenuItemSelectedListener createMenuItemListener() {
        return new FilterMenu.MenuItemAdapter.OnMenuItemSelectedListener() {
            @Override
            public void onMenuItemSelected(String item, int position) {
                mFilterMenu.dismissFilterMenu();
                if (TextUtils.equals(item, getString(R.string.reply_delete))) {
                    ((ReplyDetailFragment) mFragment).showDelReplyConfirmDialog();
                } else if (TextUtils.equals(item, getString(R.string.reply_edit))) {
                    ((ReplyDetailFragment) mFragment).onReplyEdit();
                } else if (TextUtils.equals(item, getString(R.string.quiz_detail_share))) {
                    ((ReplyDetailFragment) mFragment).onReplyShare();
                } else if (TextUtils.equals(item, getString(R.string.do_report))) {
                    ((ReplyDetailFragment) mFragment).onReplyReport();
                }
            }
        };
    }

    private FilterMenu createFilterMenu(Context context) {
        FilterMenu menu = new FilterMenu(context, R.drawable.filter_menu_bg);
        return menu;
    }

    public static class ReplyDetailFragment extends BaseFragment implements IReplyDetailView {
        public static final String strEditAnswer = "strEditAnswer";
        private final static int CODE_REPLY = 1;
        private final static int CODE_COPY = 2;
        private final static int CODE_DEL = 3;
        private FragmentReplyDetailBinding mBinding;
        private ConfirmDialog mDelDataDialog;
        private ChoiceDialog mCommentDialog;
        private ConfirmDialog mDelCommentDialog;
        private ReplyDetailPresenter mPresenter;
        private ReplyDetailAdapter mAdapter;
        private int mAnswerId, voteCount;
        private String mQuizTitle;
        private int mQuizId, mReplyCount;

        private XListView.IXListViewListener mIXListener = new XListView.IXListViewListener() {
            @Override
            public void onRefresh(XListView xListView) {
                mPresenter.requestDetail();
            }

            @Override
            public void onLoadMore(XListView xListView) {
                //                if (mAdapter.getCurrentTab() == ReplyDetailItem.ReplyTab.COMMENT) {
                //                    mPresenter.getCommentListAction(mAdapter.getCommentOffset());
                //                } else {
                //                    mPresenter.getLikeListAction(mAdapter.getLikeOffset());
                //                }
            }
        };

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_reply_detail, container, false);
            initViews();
            return mBinding.getRoot();
        }

        private void initViews() {
            mAnswerId = getArguments().getInt(EXTRA_ID);
            voteCount = getArguments().getInt(EXTRA_VOTE_COUNT);
            ExtraBaseQuestion replyTitleAct = (ExtraBaseQuestion) getArguments().getSerializable(EXTRA_BASE_QUESTION);
            mAdapter = new ReplyDetailAdapter(getActivity());
            mAdapter.setExtraBaseQuestion(replyTitleAct);
            mBinding.lvData.setPullRefreshEnable(false);
            mBinding.lvData.hideFooterView();
            mBinding.lvData.setXListViewListener(mIXListener);
            mBinding.lvData.setOnScrollListener(createOnScrollListener());
            mBinding.lvData.setAdapter(mAdapter);
            mPresenter = new ReplyDetailPresenter(this, mAnswerId);
            mPresenter.requestDetail();

            EventBusUtil.registerEvent(mPresenter);
            EventBusUtil.registerEvent(mAdapter);

            AppBus.getInstance().register(this);
        }

        private AbsListView.OnScrollListener createOnScrollListener() {
            return new XListView.OnXScrollListener() {
                @Override
                public void onXScrolling(View view) {

                }

                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {

                }

                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    int viewType = view.getAdapter().getItemViewType(view.getFirstVisiblePosition());
                    EventBusUtil.post(new TitleEvent(TitleEvent.EVENT_REPLY_TITLE, viewType > ReplyDetailItem.TYPE_REPLY_MAIN ? getQuizTitle() : getString(R.string.title_reply_detail)));
                }
            };
        }

        @Subscribe
        public void onChanged(String str) {
            if (str.equals(strEditAnswer))
                mPresenter.requestDetail();
        }

        public void onReplyReport() {
            FeedbackActivity.start(getActivity(), mAnswerId, false);
        }

        public void onReplyEdit() {
            EditAnswerActivity.start(getActivity(), mPresenter.mDetail, voteCount);
        }

        @Override
        public int getPageLength() {
            return super.getPageLength();
        }

        @Override
        public void onDestroyView() {
            EventBusUtil.unregisterEvent(mAdapter);
            EventBusUtil.unregisterEvent(mPresenter);
            super.onDestroyView();
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            AppBus.getInstance().unregister(this);
        }

        @Override
        public void setPullLoadEnable(boolean enable) {
            mBinding.lvData.setPullRefreshEnable(true);
            mBinding.lvData.setPullLoadEnable(enable);
            mBinding.lvData.stopRefresh();
            mBinding.lvData.stopLoadMore();
        }

        @Override
        public int getQuizId() {
            return mQuizId;
        }

        @Override
        public String getQuizTitle() {
            return mQuizTitle;
        }

        @Override
        public int getReplyCount() {
            return mReplyCount;
        }

        @Override
        public void showDetailData(PbBean.PbResQuestionFindAnswer body) {
            mAdapter.setDetailData(body);
            mQuizId = body.getQuestionId();
            mQuizTitle = body.getQuestionTitle();
            mReplyCount = body.getQuestionAnswerCount();
        }

        @Override
        public int getAdapterCount() {
            return mAdapter.getCount();
        }

        @Override
        public void showBottomView(final int commentCount, int likeCount) {
            mBinding.itemDetailBottom.getRoot().setVisibility(View.VISIBLE);
            mBinding.itemDetailBottom.tvComment.setText(getContext().getString(R.string.reply_bottom_comment, "" + commentCount));
            mBinding.itemDetailBottom.tvPraise.setText(getContext().getString(R.string.reply_bottom_like, ""+likeCount));
            mBinding.itemDetailBottom.flComment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ReplyAnswerCmtActivity.startActivity(getContext(), mAnswerId, PbBean.PbSignNavType.LINK_TYPE_QUESTION_ANSWER);
                }
            });

            mBinding.itemDetailBottom.flPraise.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPresenter.doPraiseAction(v);
                }
            });

        }

        @Override
        public void showPraiseView(boolean isLike) {
            mBinding.itemDetailBottom.tvPraise.setSelected(isLike);
        }

        @Override
        public void onReplyShare() {
            mPresenter.doShareAction(getContext());
        }

        @Override
        public void showCommentChoiceDialog(final PbBean.PbBaseComment comment, boolean isAuthor) {
            mCommentDialog = new ChoiceDialog(getActivity());
            List<ChoiceDialog.ChoiceItem> items = new ArrayList<>();
            if (isAuthor) {
                items.add(new ChoiceDialog.ChoiceItem(CODE_COPY, getString(R.string.dialog_choice_copy)));
                items.add(new ChoiceDialog.ChoiceItem(CODE_DEL, getString(R.string.dialog_choice_del)));
            } else {
                items.add(new ChoiceDialog.ChoiceItem(CODE_REPLY, getString(R.string.dialog_choice_reply)));
                items.add(new ChoiceDialog.ChoiceItem(CODE_COPY, getString(R.string.dialog_choice_copy)));
            }
            mCommentDialog.setChoiceItems(items);
            mCommentDialog.setCallbackListener(new ChoiceDialog.CallbackListener() {
                @Override
                public void onItemClick(ChoiceDialog.ChoiceItem item) {
                    if (comment == null)
                        return;
                    switch (item.getCode()) {
                        case CODE_REPLY:
                            mPresenter.toQuizReplyCommentAddActivity(comment.getId(), comment.getUserInfo().getNickname());
                            break;
                        case CODE_COPY:
                            mPresenter.doCopyContentAction(comment.getContent());
                            break;
                        case CODE_DEL:
                            mPresenter.showDelCommentDialog(comment.getId());
                            break;
                    }
                }
            });
            mCommentDialog.show();
        }


        //        @Override
        //        public void setCurrentTab(ReplyDetailItem.ReplyTab tab) {
        //            mAdapter.setCurrentTab(tab);
        //        }
        //
        //
        //        @Override
        //        public ReplyDetailItem.ReplyTab getCurrentTab() {
        //            return mAdapter.getCurrentTab();
        //        }
        @Override
        public void showDelCommentDialog(final int commentId) {
            if (mDelCommentDialog == null) {
                mDelCommentDialog = new ConfirmDialog(getActivity(), getString(R.string.dialog_toast_del_comment), getString(R.string.guide_delcomment_cancel_btn), getString(R.string.guide_delcomment_sure_btn));
            }
            mDelCommentDialog.setCallbackListener(new ConfirmDialog.CallbackListener() {
                @Override
                public void clickNo() {
                }

                @Override
                public void clickYes() {
                    mPresenter.doDelCommentAction(commentId, PbBean.PbSignNavType.LINK_TYPE_QUESTION_ANSWER);
                }
            });
            mDelCommentDialog.show();
        }

        @Override
        public void refreshLikes(List<PbBean.PbUserSimple> likes, int likeCount) {
            //            mAdapter.refreshLikeCount(likeCount);
            mAdapter.refreshLikes(mAnswerId, likes, likeCount);
        }

        @Override
        public BaseFragment getFragment() {
            return this;
        }

        @Override
        public void onHeadActionClick() {

        }

        public boolean titleMenuEnabled() {
            return View.VISIBLE == mBinding.itemDetailBottom.getRoot().getVisibility();
        }

        //        @Override
        //        public void refreshComments(List<PbBean.PbBaseComment> comments, int commentCount) {
        //            mAdapter.refreshCommentCount(commentCount);
        //            mAdapter.refreshComments(comments);
        //        }
        //
        //        @Override
        //        public void loadMoreComments(List<PbBean.PbBaseComment> comments) {
        //            mAdapter.loadMoreComments(comments);
        //        }
        public void showDelReplyConfirmDialog() {
            if (mDelDataDialog == null) {
                mDelDataDialog = new ConfirmDialog(getActivity(), getString(R.string.dialog_del_reply), getString(R.string.dialog_del_cancel), getString(R.string.dialog_del_sure));
                mDelDataDialog.setCallbackListener(new ConfirmDialog.CallbackListener() {
                    @Override
                    public void clickNo() {

                    }

                    @Override
                    public void clickYes() {
                        mPresenter.doDelReplyAction();
                    }
                });
            }
            mDelDataDialog.show();
        }
        //
        //        @Override
        //        public void loadMoreLikes(List<PbBean.PbUserSimple> likes) {
        //            mAdapter.loadMoreLikes(likes);
        //        }
    }

}
